import modelExtend from 'dva-model-extend'
import api from 'api'
import { pageModel } from 'utils/model'
import {t} from "@lingui/macro";
const { pathToRegexp } = require("path-to-regexp")
const { queryUserOptions, listNotification, createNotification, updateNotification, deleteNotification } = api

export default modelExtend(pageModel, {
  namespace: 'admin_notification',
  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
    userOptions: [],
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/admin_notification').exec(location.pathname)) {
         // let payload = location.query || { page: 1, pageSize: 10 }
          dispatch({
            type: 'query',
            payload: {
              ...location.query,
            },
          })

          dispatch({
            type: 'queryUserOptions',
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const data = yield call(listNotification, payload)
      if (data.success) {
        //对数据进行处理
        let list = [];
        data.payload.list.forEach(item => {
          item.isRead = item.isRead == 0 ? t`No` : t`Yes`;
          list.push(item)
        })
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.payload.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.payload.total,
            },
          },
        })
      } else {
        throw data
      }
    },
    *queryUserOptions({ payload }, { call, put }) {
      const data = yield call(queryUserOptions, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            userOptions: data.payload,
          },
        })
      } else {
        throw data
      }
    },
    *create({ payload }, { call, put }) {
      const data = yield call(createNotification, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *update({ payload }, { select, call, put }) {
      const id = yield select(({ user }) => user.currentItem.id)
      const newUser = { ...payload, id }
      const data = yield call(updateNotification, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    *delete({ payload }, { select, call, put }) {
      const data = yield call(deleteNotification, {ids:payload})
      if (!data.success) {
        throw data
      }
    },
  },
  reducers: {
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
  },
})
